<?php

namespace api\resource\controller;

use think\Db;
use think\Validate;
//use cmf\controller\RestBaseController;
use cmf\controller\RestUserBaseController;


class TablesController extends RestUserBaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //根据 项目类型id 查出该业务员 关联的

        exit;
    }

    /**
     * 显示创建项目.
     *必须 project_type_id 项目类型id  项目名字name
     * @return \think\Response
     */
    public function addProject()
    {
        $role = $this->getUserRole();   //  获取该用户角色

        if (!($role == '业务员')) $this->error("非业务员不能添加!");

        $validate = new Validate([
            'project_type_id' => 'require',
            'name'            => 'require',
        ]);

        $validate->message([
            'project_type_id.require' => '请输入项目类型!',
            'name'                    => '请输入项目名',
        ]);
        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $project_data['yewu_id'] = $this->getUserId();

        $project_data['project_type_id'] = $data['project_type_id'];
        $project_data['company_name'] = $data['name'];
        $project_data['create_time']     = time();
        $pro_id                          = Db::name('project')->insertGetId($project_data);

        $return_add_data['pro_id'] = $pro_id;
        $this->success("提交成功!", $return_add_data);
    }

    /**
     * 显示创建项目.
     *必须 project_type_id 项目类型id  项目名字name
     * @return \think\Response
     */
    public function addProjects()
    {
        $role = $this->getUserRole();   //  获取该用户角色

        if (!($role == '业务员')) $this->error("非业务员不能添加!");

        $validate = new Validate([
            'project_type_id' => 'require',
            'name'            => 'require',
            'year'            => 'require',
        ]);

        $validate->message([
            'project_type_id.require' => '请输入项目类型!',
            'name'                    => '请输入项目名',
            'year'                    => '请输入年度',
        ]);
        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $return_add_data = [];
        try {
            $data['project_type_id'] = explode(',', $data['project_type_id']);
            foreach ($data['project_type_id'] as $k=>$v) {

                //查是否存在这个类型的公司 没有再添加
                $where['company_name'] = $data['name'];
                $where['project_type_id'] = $v;
                $project_exist_data =  Db::name('project')->where($where)->find();
                if ($project_exist_data) {
                    //填出本次循环
                    continue;
                }
                $project_data['yewu_id'] = $this->getUserId();
                $project_data['project_type_id'] = $v;
                $project_data['company_name'] = $data['name'];
                $project_data['create_time']     = time();
                $project_data['more']     = $data['year'];
                $pro_id                          = Db::name('project')->insertGetId($project_data);

                $return_add_data[$k]['pro_id'] = $pro_id;
            }
        } catch (\Exception $e) {
            $this->error('不知道什么鬼错误！');
        }

        
        $this->success("提交成功!", $return_add_data);
    }

    /**
     * 显示创建资源表单页.
     *最少 pro_id 项目id  biao_name
     * @return \think\Response
     */
    public function create()
    {
        $role = $this->getUserRole();   //  获取该用户角色

        if (!($role == '业务员' || $role == '技术员')) $this->error("非业务员或技术员不能添加!");
        //如果没有项目pro_id 就插入数据后创建一个，然后创建cmf_project表新数据 有pro_id就添加一条数据
        $validate = new Validate([
            'project_type_id' => 'require',
            'biao_id'         => 'require',
        ]);

        $validate->message([
            'project_type_id.require' => '请输入项目类型!',
            'biao_id'                 => '请输入表名id',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
//        $this->success("提交成功!");
        $biao_name = 'biao' . $data['biao_id'];
        if (isset($data['pro_id'])) {
            //有pro_id就添加一条数据
            $new_data['pro_id'] = $data['pro_id'];

            unset($data['pro_id'], $data['biao_id'], $data['project_type_id']);


            $new_data['content'] = json_encode($data, JSON_UNESCAPED_UNICODE);


            $id = Db::name($biao_name)->insertGetId($new_data);

        } else {

            //如果没有项目pro_id 就插入数据后创建一个

            //然后创建cmf_project表新数据
            $project_data['yewu_id'] = $this->getUserId();
//            $project_data['yewu_id'] = 6;

            $project_data['project_type_id'] = $data['project_type_id'];
            $project_data['create_time']     = time();
            $pro_id                          = Db::name('project')->insertGetId($project_data);

            //插入完整的数据到biao_name
            $new_data['pro_id'] = $pro_id;

            unset($data['biao_id'], $data['project_type_id']);


            $new_data['content'] = json_encode($data, JSON_UNESCAPED_UNICODE);


            $id = Db::name($biao_name)->insertGetId($new_data);


            $return_add_data['pro_id'] = $pro_id;
        }


        if (empty($id)) {
            $this->error('提交失败，请重试!');
        }

        $return_add_data['id'] = $id;
        $this->success("提交成功!", $return_add_data);

    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //

    }

    /**
     * 显示指定的资源
     *
     * @param  int $id
     * @return \think\Response
     */
    public function read($self = null)
    {

        $validate = new Validate([
            'pro_id'  => 'require',
            'biao_id' => 'require',
        ]);

        $validate->message([
            'pro_id.require'  => '请输入项目id!',
            'biao_id.require' => '请输入表id!',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }


        //查出 表数据
        $biao_name       = 'biao' . $data['biao_id'];
        $where['pro_id'] = $data['pro_id'];
        $biao_data       = Db::name($biao_name)
            ->where($where)
            ->select()->toArray();

        foreach ($biao_data as &$val) {
            $val['pzhu'] = $val['remarks'];
            unset($val['remarks']);
        }

        //获取项目类型表关联数组成功

        $project_type_arr = Db::view('project_type', 'l_id')
            ->view('project', 'id', 'project.project_type_id=project_type.id')
            ->where('project.id', '=', $data['pro_id'])
            ->find();

        if (!$project_type_arr['l_id']) $this->error("服务器繁忙!");
        $project_type_arr = explode(',', $project_type_arr['l_id']);

//        dump($biao_data);

        if ($biao_data) {
//            $biao_data[0]['content'] = htmlspecialchars_decode($biao_data[0]['content']);
            $biao_data[0]['content'] = json_decode($biao_data[0]['content']);

            if (isset($biao_data[0]['content']->items)) {

                foreach ($biao_data[0]['content']->items as &$v) {

                    $v = htmlspecialchars_decode($v);
                }
//                dump($biao_data[0]['content']->items);
//                exit;
//                foreach ($biao_data[0]['content']->items as &$v) {
//                    //检查是字符串或是数组 然后如果是数组就转换成字符串
//                    if (!is_array($v)) {
//                        $v = htmlspecialchars_decode($v);
//                    }
//                    dump($v);
//                    exit;
//                }

            } else {
                foreach ($biao_data[0]['content'] as &$v) {
                    //检查是字符串或是数组 然后如果是数组就转换成字符串
                    if (!is_array($v)) {
                        $v = htmlspecialchars_decode($v);
                    }
                }
            }

        }
        if ($self) {
            return $biao_data;
        }
        $new_data['data'] = $biao_data;

        $new_data['showArr'] = $project_type_arr;

        $this->success("查询成功!", $new_data);

    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int $id
     * @return \think\Response
     */
    public function edit()
    {
        $role = $this->getUserRole();

        if ($role != '技术员' && $role != '业务员') {
            $this->error("你没有权限进行此操作!");
        }

        $validate = new Validate([
            'id'      => 'require',
            'biao_id' => 'require',
        ]);

        $validate->message([
            'id.require'      => '请输入数据id!',
            'biao_id.require' => '请输入表id!',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }


        $id        = $data['id'];
        $biao_name = 'biao' . $data['biao_id'];

        unset($data['id'], $data['biao_id']);
        $new_data['content'] = json_encode($data);
        //先删除改id  的content
        $bool = Db::name($biao_name)
            ->where('id', $id)
            ->update($new_data);

        if (empty($bool)) {
            $this->error('提交失败，请重试!');
        }

        $this->success("提交成功!");


    }

    /**
     * 保存更新的资源 备注
     *
     * @param  \think\Request $request
     * @param  int $id
     * @return \think\Response
     */
    public function update()
    {
//        $role = $this->getUserRole();
//
//        if ($role != '审核员') {
//            $this->error("你没有权限进行此操作!");
//        }

        $validate = new Validate([
            'id'      => 'require',
            'biao_id' => 'require',
        ]);

        $validate->message([
            'id.require'      => '请输入数据id!',
            'biao_id.require' => '请输入表id!',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }


        $id        = $data['id'];
        $biao_name = 'biao' . $data['biao_id'];

        unset($data['id'], $data['biao_id']);
        $new_data['remarks'] = $data['pzhu'];
        //先删除改id  的content
        $bool = Db::name($biao_name)
            ->where('id', $id)
            ->update($new_data);

        if (empty($bool)) {
            $this->error('提交失败，请重试!');
        }

        $this->success("提交成功!");
    }


    /**
     * 删除指定资源
     *
     * @param  int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
        $validate = new Validate([
            'id'      => 'require',
            'biao_id' => 'require',
        ]);

        $validate->message([
            'id.require'      => '请输入数据id!',
            'biao_id.require' => '请输入表id!',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $id        = $data['id'];
        $biao_name = 'biao' . $data['biao_id'];

        $new_data['content'] = '';

        //先删除改id  的content
        $bool = Db::name($biao_name)
            ->where('id', $id)
            ->update($new_data);

        if (empty($bool)) {
            $this->error('提交失败，请重试!');
        }

        $this->success("提交成功!");
    }

    /**
     * 删除指定资源
     *
     * @param  int $id
     * @return \think\Response
     */
    public function del()
    {
        $role = $this->getUserRole();   //  获取该用户角色

        if (!($role == '业务员' || $role == '超级管理员'|| $role == '管理员')) $this->error("非业务员或超级管理员或管理员不能删除!");

        $validate = new Validate([
            'id'      => 'require',
        ]);

        $validate->message([
            'id.require'      => '请输入项目id!',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $id        = $data['id'];
        //先删除改id  的content
        $bool = Db::name('project')
            ->where('id', $id)
            ->delete();

        if (empty($bool)) {
            $this->error('提交失败，请重试!');
        }
        $this->success("删除成功!");
    }


    /**
     * 显示指定的资源
     *
     * @param  int $id
     * @return \think\Response
     */
    public function readSelf($pro_id, $biao_id)
    {

        //查出 表数据
        $biao_name       = 'biao' . $biao_id;
        $where['pro_id'] = $pro_id;
        $biao_data       = Db::name($biao_name)
            ->where($where)
            ->select()->toArray();

        foreach ($biao_data as &$val) {
            $val['pzhu'] = $val['remarks'];
            unset($val['remarks']);
        }




        if ($biao_data) {
            $biao_data[0]['content'] = json_decode($biao_data[0]['content']);

            if (isset($biao_data[0]['content']->items)) {

                foreach ($biao_data[0]['content']->items as &$v) {

                    $v = htmlspecialchars_decode($v);
                }


            } else {
                foreach ($biao_data[0]['content'] as &$v) {
                    //检查是字符串或是数组 然后如果是数组就转换成字符串
                    if (!is_array($v)) {
                        $v = htmlspecialchars_decode($v);
                    }
                }
            }

        }

        return $biao_data;


    }
}
